﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Messaging;
using Utility;
using Common.Logging;

namespace MonitorServer
{
    public class MessageQueueService : IMessageQueue
    {

        MessageQueue q;
        IMessageFormatter formatter = new System.Messaging.XmlMessageFormatter();
        private static readonly MessageQueueService instance = new MessageQueueService();
        protected ILog log = LogFactory.CreateFileLog();

        private string QueueName
        {
            get
            {
                return ConfigurationManager.AppSettings["QueueName"];
            }
        }
        private MessageQueueService()
        {
            try
            {
                if (!IsQueueAvailable())
                {
                    q = MessageQueue.Create(QueueName);
                    q.SetPermissions("Everyone", MessageQueueAccessRights.FullControl);
                }
                else
                {
                    q = new MessageQueue(QueueName);
                }
            }
            catch (Exception ex)
            {
                log.Error("MessageQueueService Constructor issue.", ex);
            }
        }
        public bool IsQueueAvailable()
        {
            return MessageQueue.Exists(QueueName);
            //var queue = new MessageQueue(QueueName);

            //return queue != null;
            //queue.SetPermissions("ws-dc-03\\Administrator", MessageQueueAccessRights.ReceiveMessage);
            //try
            //{
            //    queue.Peek(new TimeSpan(0, 0, 5));
            //    return true;
            //}
            //catch (MessageQueueException ex)
            //{
            //    return ex.Message.StartsWith("Timeout");
            //}
            //catch (Exception ex)
            //{
            //    log.Error("", ex);
            //    return false;
            //}
        }

        public static MessageQueueService CrateInstance()
        {
            return instance;
        }

        public void SendRequest(RequestEntity r)
        {
            try
            {
                Message m = new Message(r);
                m.Formatter = formatter;
                q.Send(m);
            }
            catch (Exception ex)
            {
                log.Error("Save Request Error", ex);
            }
        }

        public void SendAction(HtmlAction a)
        {
            try
            {
                Message m = new Message(a);
                m.Formatter = formatter;
                q.Send(m);
            }
            catch (Exception ex)
            {
                log.Error("Save Request Error", ex);
            }
        }

        public string RequestSave()
        {
            string result = string.Empty;
            try
            {
                log.Info("Receive Start...");

                ((XmlMessageFormatter)q.Formatter).TargetTypes = new Type[] { typeof(RequestEntity) };
                Message m = q.Receive();

                if (m == null) log.Info(string.Format("m:[{0}]", m));
                if (m.Body != null)
                {
                    log.Info(string.Format("m:[{0}],m.body:[{1}]", m, m.Body));
                   
                    RequestEntity request = m.Body as RequestEntity;
                    if (request != null)
                    {
                        request.Insert();
                        result = request.Url;
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("Save Request Error", ex);
                throw ex;
            }
            return result;
        }

        public void ActionSave()
        {
            try
            {
                ((XmlMessageFormatter)q.Formatter).TargetTypes = new Type[] { typeof(HtmlAction) };
                Message m = q.Receive();
                HtmlAction action = m.Body as HtmlAction;
                if (action != null)
                {
                    action.Insert();
                }
            }
            catch (Exception ex)
            {
                log.Error("Save Request Error", ex);
                throw ex;
            }
        }
    }
}
